<?php

namespace app\app\controller;

use app\app\model\ProjectDKModel;
use app\app\model\ProjectFileInfoModel;
use app\app\model\ProjectReportModel;
use app\app\model\ProjectTypicalProblems;
use app\app\model\ProjectViolationNewModel;
use app\app\model\ProjectZrrCommentModel;
use app\app\model\ProjectZrrDetailModel;
use app\app\model\RandModel;
use app\BaseController;
use app\app\model\ProjectModel;
use app\app\model\ProjectRiskModel;
use app\app\model\ProjectTDModel;
use app\app\model\ProjectZrrModel;
use app\app\model\UserModel;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;


class ProjectZrr extends BaseController
{

    public function list()
    {
        $dw_type = input('dwType', '');
        $city = input('city', '');
        $dw_name = input('dwName', '');
        $project_name = input('projectName', '');
        //$page_size = input('pageSize', '20');


        $where = [];

        //按照分类类型筛选

        if ($dw_type) {
            $where[] = ['a.dw_type', '=', $dw_type];
        } else {
            $where[] = ['a.dw_type', 'in', ['劳务分包', '专业分包']];
        }

        if ($project_name) $where[] = ['a.project_name', 'like', '%' . $project_name . '%'];

        if ($dw_name) $where[] = ['a.dw_name', 'like', '%' . $dw_name . '%'];

        $where[] = ['b.project_period', 'in', '2,4,1'];

        $group = ProjectZrrModel::alias('a')
            ->field('COUNT(a.id) as total, a.id,a.project_name,a.dw_name,a.dw_type,b.id,b.link_project_id,c.project_name as project_main_name,c.id as main_id,c.kg_time as kg_main_time,c.tc_time as tc_main_time')
            ->leftjoin('t_project b', 'a.project_id = b.id')
            ->leftjoin('t_project c', 'b.link_project_id = c.id')
            ->where($where);

//            $group = ProjectZrrModel::alias('a')
//                ->field("a.dw_name, a.project_id, b.city")
//                ->join('t_project b', 'a.project_id = b.id')
//                ->where('a.dw_type', 'like', '%' . $dw_type . '%')
//                ->where('a.dw_name', 'like', '%' . $dw_name . '%')
//                ->where('a.project_name', 'like', '%' . $project_name . '%')
//                ->where('b.city', 'like', '%' . $city . '%');
//
        $group_count = ProjectZrrModel::alias('a')
            ->leftjoin('t_project b', 'a.project_id = b.id')
            ->leftjoin('t_project c', 'b.link_project_id = c.id')
            ->where($where)->group('a.dw_name')->count();
//        $group_count = $group->count();
        $group_list = $group->group('a.project_name')->select()->toarray();
        $info = $group_list;
        $tmp_arr = array();
        $temp = array();
        foreach ($info as $k => $v) {
            if (!in_array($v['main_id'], $tmp_arr)) {
                $tmp_arr[$k] = $v['main_id'];
                $temp[$k]['id'] = $v['main_id'];
                $temp[$k]['project_name'] = $v['project_main_name'];
            }
        }
        foreach ($temp as $key => $value) {
            foreach ($info as $k => $v) {
                if ($value['id'] == $v['link_project_id']) {
                    $temp[$key]['children'][] = $v;
                }
            }
            $group_list = $temp;
        }


//        var_dump($group_list);die();

//        $project = ProjectModel::alias('a')
//            ->field("a.project_name, a.id, b.id as group_id")
//            ->join('t_project_zrr b', 'a.id = b.project_id');
//
//        $project_list = $project->select();
//
//        $group_list = ProjectZrrModel::alias('a')
//            ->field("COUNT(b.id) as total, a.id ,a.dw_name")
//            ->join('t_project b', 'a.project_id = b.id')
//            ->where('a.dw_type', 'like', '%'.$dw_type.'%')
//            ->where('b.city', 'like', '%'.$city.'%')
//            ->group('b.id')
//            ->order('total DESC')
//            ->select();
//
//        $group_count = $project->count();


        $res = array(
//            'info' => $info,
            'total' => $group_count,
//            'project_list' => $project_list,
            'group_list' => $group_list,
        );
        $this->success('success', $res);
    }


    public function info()
    {
        $id = input('project_id', '');
        $dw_type = input('dw_type', '');
        $where = [];
        if ($dw_type) {
            $where[] = ['dw_type', '=', $dw_type];
        } else {
            $where[] = ['dw_type', 'in', ['劳务分包', '专业分包']];
        }
        $list = ProjectZrrModel::where($where)->where('1 = 1')
            ->where('project_id', $id)->select();
        $this->success('success', $list);
    }

    /**
     * 队伍列表
     * @return void
     * @throws DbException
     */
    public function groupList()
    {
        $type = input('type', '');
        empty($type) && $this->error('请传入类型');

        $type = $type == '施工单位' ? ['劳务分包', '专业分包'] : [$type];

        $page_size = input('pageSize', '20');

        $list = ProjectZrrModel::where('dw_type', 'in', $type)
            ->paginate($page_size);

        empty($list) && $this->error('找不到符合条件的队伍');

        $this->success('success', $list);
    }

    /**
     * 给指定责任人评分
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function personLiableScore()
    {
        $id = input('id/s');
        empty($id) && $this->error('请传入id');

        $point = input('point/s');
        empty($point) && $this->error('请传入point');

        $content = input('content/s');
        empty($content) && $this->error('请输入评论内容');

        $pic_id = input('pic_id/s');
//        empty($pic_id) && $this->error('请传入pic_id');

        $data = [
            'detail_id' => $id,
            'score' => $point,
            'content' => $content,
            'pic_id' => $pic_id,
            'create_time' => date('Y-m-d H:i:s'),
        ];
        (new ProjectZrrCommentModel())->save($data);

        $detail = ProjectZrrDetailModel::where('id', $id)->find();
        empty($detail) && $this->error('未找到符合条件的责任人');

        empty($detail['score']) && $detail->score = 100;

        $detail->score = floatval($detail->score) - floatval($point);
        $detail->save();

        $this->success('success');
    }

    /**
     * 添加责任人
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function personLiableAdd()
    {
        $data = $this->request->param();
        if (isset($data['id'])) {
            unset($data['id']);
        }
        empty($data['link_id']) && $this->error('请传入link_id');
        empty($data['zrr_name']) && $this->error('请传入zrr_name');
        empty($data['zrr_tel']) && $this->error('请传入zrr_tel');
        empty($data['zrr_position']) && $this->error('请传入zrr_position');

        $project = ProjectZrrModel::where('id', $data['link_id'])
            ->field(['project_id', 'project_name'])
            ->find();
        empty($project) && $this->error('未找到符合条件的单位');

        (new ProjectZrrDetailModel)
            ->save(array_merge($data, $project->toArray()));

        $this->success('success');
    }

    /**
     * 编辑责任人
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function personLiableEdit()
    {
        $data = $this->request->param();

        empty($data['id']) && $this->error('请传入id');

//        empty($data['zrr_name']) && $this->error('请传入zrr_name');
//        empty($data['zrr_tel']) && $this->error('请传入zrr_tel');

        $comment = ProjectZrrDetailModel::where('id', $data['id'])->find();

        empty($comment) && $this->error('无效ID');

        $comment->allowField(['zrr_name', 'zrr_tel', 'zrr_identity'])->save($data);

        $this->success('success');
    }

    /**
     * 获取符合条件的单位列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function personLiableList()
    {
        $project_id = input('project_id/s', '');
        if (empty($project_id)) $this->error('请传入project_id');

        $type = input('type/s', '');
        if (empty($type)) $this->error('请传入type');

        $person_liable = ProjectZrrModel::where('project_id', $project_id)
            ->where('dw_type', $type)
            ->field(['id', 'dw_name', 'dw_type'])
            ->find();

        empty($person_liable) && $this->error('未找到符合条件的单位');

        $data = self::getPersonLiableDefaultArray($type);

        $result = [];
        switch ($type) {
            case '施工单位':
                $person_liable_self = ProjectZrrModel::where('project_id', $project_id)
                    ->where('dw_type', $type)
                    ->field(['id', 'dw_name', 'dw_type', 'parent_id'])
                    ->find();
                $person_liable_self['dw_type'] = '自有单位';

                $person_liable_other = ProjectZrrModel::where('parent_id', $person_liable['id'])
                    ->field(['id', 'dw_name', 'dw_type', 'parent_id'])
                    ->select()
                    ->toArray();

                $person_liable_son = $person_liable_other;
                $person_liable_son[] = $person_liable_self;
                $tmp = array_column($person_liable_son, 'id', 'id');
                array_multisort($person_liable_son, SORT_DESC, $tmp);

                foreach ($person_liable_son as $person_liable) {

                    $zrr_detail = ProjectZrrDetailModel::where('link_id', $person_liable['id'])
                        ->where('status', 1)
                        ->field(['id', 'zrr_name', 'zrr_tel', 'zrr_position', 'zrr_identity', 'score'])
                        ->select();

                    foreach ($zrr_detail as $v) {
                        $v = $v->toArray();
                        if ($v['score'] === null) $v['score'] = 100;

                        $data[$person_liable['dw_type']][$v['zrr_position']]['position'] = $v['zrr_position'];
                        $data[$person_liable['dw_type']][$v['zrr_position']]['children'][] = $v;
                    }

                    foreach ($data as $k => $v) {
                        $data[$k] = array_values($v);
                    }

                    $result[] = [
                        'id' => $person_liable['id'],
                        'parent_id' => $person_liable['parent_id'],
                        'name' => $person_liable['dw_name'],
                        'type' => $person_liable['dw_type'],
                        'list' => $data[$person_liable['dw_type']]
                    ];
                }

                unset($v);

                $tmp = [];
                foreach ($result as $v) {
                    if (!empty($v['parent_id'])) {
                        $tmp[$v['parent_id']]['children'][] = $v;
                    } else {
                        $tmp_children = $tmp[$v['id']]['children'] ?? [];
                        $tmp[$v['id']] = $v;
                        $tmp[$v['id']]['children'] = $tmp_children;
                    }
                }
                $result = array_values($tmp);

                $tmp_result = [];
                foreach ($result as $k => $v) {
                    if (empty($v['children'])) continue;
                    $tmp_result[$k] = $v;
                    unset($tmp_result[$k]['children']);

                    $tmp = [];
                    foreach ($v['children'] as $b) {
                        $tmp[$b['type']][] = $b;
                    }

                    $tmp_result_end = [];
                    foreach ($tmp as $x => $y) {
                        $tmp_result_end[$x] = [
                            'type' => $x,
                            'list' => $y,
                        ];
                        $tmp_result_end = array_values($tmp_result_end);
                    }

                    $tmp_result[$k]['children'] = $tmp_result_end;
                }
                $result = $tmp_result;
                unset($tmp_result);

                break;
            default:
                $zrr_detail = ProjectZrrDetailModel::where('link_id', $person_liable['id'])
                    ->where('status', 1)
                    ->field(['id', 'zrr_name', 'zrr_tel', 'zrr_position', 'zrr_identity', 'score'])
                    ->select();

                foreach ($zrr_detail as $v) {
                    $data[$v['zrr_position']]['position'] = $v['zrr_position'];
                    $data[$v['zrr_position']]['children'][] = $v;
                }

                $result = [
                    [
                        'id' => $person_liable['id'],
                        'name' => $person_liable['dw_name'],
                        'type' => $person_liable['dw_type'],
                        'list' => array_values($data)
                    ]
                ];

                unset($v);

                $tmp = [];
                foreach ($result as $v) {
                    $tmp[$v['type']]['type'] = $v['type'];
                    $tmp[$v['type']]['list'] = $v;
                }
                $result = array_values($tmp);
        }

        $this->success('success', $result);

    }

    /**
     * 获取符合条件的单位人员列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPersonLiableList()
    {
        $id = input('id/s', '');
        empty($id) && $this->error('请传入id');

        $personLiableCompany = ProjectZrrModel::where('id', $id)
            ->field(['id', 'dw_type', 'dw_name'])
            ->find();
        empty($personLiableCompany) && $this->error('未找到符合条件的单位');

        switch ($personLiableCompany['dw_type']) {
            case '劳务分包':
            case '专业分包':
                $type = '施工单位=>' . $personLiableCompany['dw_type'];
                break;
            case '施工单位':
                $type = '施工单位=>自有单位';
                break;
            default:
                $type = $personLiableCompany['dw_type'];
        }

        $data = self::getPersonLiableDefaultArray($type);

        $personLiable = ProjectZrrDetailModel::where('link_id', $id)
            ->where('status', 1)
            ->select();
        empty($personLiable) && $this->error('未找到符合条件的人员列表');

        $personLiable = $personLiable->toArray();

        foreach ($personLiable as $v) {
            $data[$v['zrr_position']]['position'] = $v['zrr_position'];
            $data[$v['zrr_position']]['children'][] = $v;
        }

        $data = array_values($data);

        $result = [
            'id' => $personLiableCompany['id'],
            'dw_name' => $personLiableCompany['dw_name'],
            'list' => $data,
        ];

        $this->success('success', $result);
    }

    /**
     * 获取责任人职位表
     * @param string $type 单位类型
     * @return array
     */
    public static function getPersonLiableDefaultArray(string $type = ''): array
    {
        $default_data = [
            '业主单位' => [
                '项目经理',
                '项目副经理',
                '建设协调专职',
                '安全专职',
                '质量专职',
                '技术专职',
                '造价专职',
                '属地协调联系人',
                '物资协调联系人',
                '通信专职',
                '运检专业联系人',
            ],
            '监理单位' => [
                '总监',
                '总监代表',
                '安全总监',
                '专监',
                '监理员',
            ],
            '施工单位' => [
                '自有单位' => [
                    '施工项目经理',
                    '施工项目副经理',
                    '施工项目总工',
                    '施工安全员',
                    '施工质检员',
                    '施工技术员',
                    '班长兼指挥',
                    '班组安全员',
                    '技术兼质监员',
                ],
                '专业分包' => [
                    '专业分包项目经理',
                    '分包总工',
                    '分包安全员',
                    '分包质检员',
                    '分包技术员',
                    '班长兼指挥',
                    '班组安全员',
                    '技术兼质监员',
                ],
                '劳务分包' => [
                    '劳务负责人',
                    '分包安全员',
                    '分包技术员',
                    '班组长',
                    '班组安全员',
                    '班组技术员',
                ],
            ],
            '设计单位' => [
                '设总',
                '设计工代'
            ],
        ];

        if (empty($type)) return $default_data;

        if (strpos($type, '=>')) {
            list($a, $b) = explode('=>', $type);
            $data = $default_data[$a][$b];
        } else {
            $data = $default_data[$type];
        }

        $tmp = [];
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $tmp2 = [];
                foreach ($v as $y) {
                    $tmp2[$y] = [
                        'position' => $y,
                        'children' => [],
                    ];
                }
                $tmp[$k] = $tmp2;
            } else {
                $tmp[$v] = [
                    'position' => $v,
                    'children' => [],
                ];
            }
        }
        $data = $tmp;
        unset($tmp);

        return $data;
    }

    /**
     * 查询符合条件的评价
     * @return void
     * @throws DbException
     */
    public function personLiableCommentList()
    {
        $id = input('id/s');
        $page_size = input('pageSize/s', '20');

        empty($id) && $this->error('请传入ID');
        $type = input('type', '1');
        if ($type == 1) {
            $comment = ProjectZrrCommentModel::alias('a')
                ->field('a.*,b.zrr_position,b.project_name,b.project_id,c.dw_name,e.project_name as mian_project_name')
                ->leftJoin('t_project_zrr_detail b', 'b.id = a.detail_id')
                ->leftJoin('t_project_zrr c', 'b.link_id = c.id')
                ->leftJoin('t_project d', 'b.project_id = d.id')
                ->leftJoin('t_project e', 'e.id = d.link_project_id')
                ->where('a.detail_id', $id)
                ->paginate($page_size);
            empty($comment) && $this->error('查询为空');

            $pic_id = array_column($comment->toArray()['data'], 'pic_id');
            $pic = ProjectFileInfoModel::whereIn('file_id', $pic_id)
                ->field(['file_path', 'file_id'])
                ->select();

            $pic = array_column($pic->toArray(), null, 'file_id');

            foreach ($comment as &$v) {
                if (!isset($pic[$v['pic_id']])) {
                    $v['pic'] = '';
                    continue;
                }
                $pic_path = str_replace('\\', '/', $pic[$v['pic_id']]);
                $v['pic'] = $pic_path;
            }
        } else {
            $comment = ProjectViolationNewModel::alias('a')
                ->field('a.*,b.zrr_position,b.project_name,b.project_id,c.dw_name,e.project_name as mian_project_name')
                ->leftJoin('t_project_zrr_detail b', 'b.id = a.zrr_detail_id')
                ->leftJoin('t_project_zrr c', 'b.link_id = c.id')
                ->leftJoin('t_project d', 'a.project_id = d.id')
                ->leftJoin('t_project e', 'e.id = d.link_project_id')
                ->where('a.zrr_detail_id', $id)
                ->where('a.score', '>', 0)
                ->paginate($page_size);
        }


        $this->success('success', $comment);
    }

    public function analysis()
    {
        $id = input('id');
        $list['violation_total'] = ProjectViolationNewModel::where('zrr_detail_id', $id)->sum('score');
        $list['comment_total'] = ProjectZrrCommentModel::where('detail_id', $id)->sum('score');
        $this->success('success', $list);
    }

    /**
     * 人员管理评价
     */
    public function personnelEvaluate()
    {
        $page_size = input('pageSize/s', '20');
        $where = "(a.score < 100 or a.violation_score <100)";

        $name = input('name', '');
        if ($name) $where .= " and a.zrr_name like '%" . $name . "%'";
        $list = ProjectZrrDetailModel::alias('a')
            ->field('a.id,a.zrr_name,format((100-a.score),1) as comment_score,format((100-a.violation_score),1) as  violation_score, format(200 - (a.score + a.violation_score), 1) as total_score,b.dw_name')
            ->leftJoin('t_project_zrr b', 'a.link_id = b.id')
            ->where($where)
            ->order('total_score', 'desc')
            ->paginate($page_size);
        $this->success('success', $list);
    }

    /**
     * 删除责任人
     * @return void
     */
    public function personLiableDel()
    {
        $id = input('id/s');
        empty($id) && $this->error('请传入id');

        ProjectZrrDetailModel::where('id', $id)->update(['status' => 0]);

        $this->success('success');
    }

    /**
     * 添加/修改责任人
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function personLiableSave()
    {
        $data = $this->request->param();

        if (empty($data['id'])) {
            $personLiable = new ProjectZrrDetailModel();
            $personLiable->status = 0;
            $personLiable->score = 100;
        } else {
            $personLiable = ProjectZrrDetailModel::where('id', $data['id'])
                ->where('status', 0)
                ->find();
        }

        if (!empty($data['project_id'])) {
            $project = ProjectModel::where('id', $data['project_id'])
                ->field(['id', 'project_name'])
                ->find();
            empty($project) && $this->error('未找到此项目');

            $data['project_name'] = $project['project_name'];
        }

        unset($data['id']);
        $personLiable->save($data);

        $this->success('success');
    }

    /**
     * 人员统计
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function stat()
    {
        // 在建工程总数
        $where = [];
        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['tc_time', '>=', $start_time];
        $where[] = ['kg_time', '<=', $end_time];
        $where[] = ['is_parent', '=', 0];
        $project_num = ProjectModel::where('project_period', 'in', [2, 4, 1])
            ->where($where)
            ->count();

        // 人员总数
        $where = [];
        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['b.tc_time', '>=', $start_time];
        $where[] = ['b.kg_time', '<=', $end_time];
//        $where[] = ['b.is_parent', '=', 0];
        $people_num = ProjectZrrDetailModel::alias('a')
            ->leftJoin('t_project b', 'a.project_id = b.id')
            ->where('a.status', 1)
            ->where($where)
            ->group('zrr_name')
            ->count();

        // 业主人员总数
        $owner_unit = ProjectZrrModel::where('dw_type', '业主单位')
            ->field(['id', 'dw_name'])
            ->select();
        $owner_unit_id = array_column($owner_unit->toArray(), 'id');
        $owner_num = ProjectZrrDetailModel::where('link_id', 'in', $owner_unit_id)
            ->where('status', 1)
            ->group('zrr_name')
            ->count();

        // 监理人员总数
        $control_unit = ProjectZrrModel::where('dw_type', '监理单位')
            ->field(['id', 'dw_name'])
            ->select();
        $control_unit_id = array_column($control_unit->toArray(), 'id');
        $control_num = ProjectZrrDetailModel::where('link_id', 'in', $control_unit_id)
            ->where('status', 1)
            ->group('zrr_name')
            ->count();

        // 施工人员总数
        $construction_unit = ProjectZrrModel::where('dw_type', '施工单位')
            ->field(['id', 'dw_name'])
            ->select();
        $construction_unit_id = array_column($construction_unit->toArray(), 'id');
        $construction_num = ProjectZrrDetailModel::where('link_id', 'in', $construction_unit_id)
            ->where('status', 1)
            ->group('zrr_name')
            ->count();

        // 分包人员总数
        $subcontract_unit = ProjectZrrModel::where('dw_type', 'in', ['劳务分包', '专业分包'])
            ->field(['id', 'dw_name'])
            ->select();
        $subcontract_unit_id = array_column($subcontract_unit->toArray(), 'id');
        $subcontract_num = ProjectZrrDetailModel::where('link_id', 'in', $subcontract_unit_id)
            ->where('status', 1)
            ->group('zrr_name')
            ->count();

        $data = [
            'project_num' => $project_num,
            'people_num' => $people_num,
            'owner_num' => $owner_num,
            'control_num' => $control_num,
            'construction_num' => $construction_num,
            'subcontract_num' => $subcontract_num,
        ];

        $this->success('success', $data);
    }

    /**
     * 公司责任人数量
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function CompanyZrrNum()
    {
        $project_name = input('project_name/s', '');
        $zrr_name = input('zrr_name/s', '');

        $where = [];
        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['b.tc_time', '>=', $start_time];
        $where[] = ['b.kg_time', '<=', $end_time];
//        $where[] = ['b.is_parent', '=', 0];

        if (!empty($project_name)) {
            $where[] = ['b.project_name', 'like', '%' . $project_name . '%'];
        }
        if (!empty($zrr)) {
            $where[] = ['a.zrr_name', 'like', '%' . $zrr_name . '%'];
        }

        $data = ProjectZrrDetailModel::alias('a')
            ->leftJoin('t_project b', 'a.project_id = b.id')
            ->leftJoin('t_project_zrr c', 'a.link_id = c.id')
            ->where('a.status', 1)
            ->where($where)
            ->field([
                'a.id',
                'a.zrr_name',
                'a.zrr_tel',
                'c.dw_name',
                'b.is_parent',
                'b.link_project_id',
                'b.id as project_id',
                'b.project_name'
            ])
            ->select();

        $project_id = array_column($data->toArray(), 'link_project_id');

        $where = [];
        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['tc_time', '>=', $start_time];
        $where[] = ['kg_time', '<=', $end_time];
//        $where[] = ['is_parent', '=', 0];

        $project = ProjectModel::where($where)
//            ->where('id ', 'in', $project_id)
            ->field(['id', 'project_name'])
            ->select();

        $project_array = [];
        foreach ($data as $v) {
            $project_array[$v['project_id']]['name'] = $v['project_name'];
            $project_array[$v['project_id']]['id'] = $v['id'];
        }
        foreach ($project as $v) {
            $project_array[$v['id']]['name'] = $v['project_name'];
            $project_array[$v['id']]['id'] = $v['id'];
        }

        $result = [];
        foreach ($data as $v) {
            if ($v['is_parent'] == 0) {
                if (isset($result[$v['project_id']])) {
                    $result[$v['project_id']]['id'] = $v['id'];
                    $result[$v['project_id']]['count']++;
                } else {
                    $result[$v['project_id']]['id'] = $v['id'];
                    $result[$v['project_id']]['count'] = 1;
                }
            } else {
                if (isset($result[$v['link_project_id']]['children'][$v['project_id']])) {
                    $result[$v['link_project_id']]['children'][$v['project_id']]['id'] = $v['id'];
                    $result[$v['link_project_id']]['children'][$v['project_id']]['count']++;
                } else {
                    $result[$v['link_project_id']]['children'][$v['project_id']]['id'] = $v['id'];
                    $result[$v['link_project_id']]['children'][$v['project_id']]['count'] = 1;
                }
            }
        }

        $result = $this->projectNameConvent($result, $project_array);

        $this->success('success', $result);
    }

    public function peopleList()
    {
        $type = input('type', '业主单位');
        $project_id = input('project_id', '业主单位');
        $where[] = ['a.project_id', '=', $project_id];
        if ($type == '施工单位') {
            $where[] = ['b.dw_type', 'in', ['劳务分包', '专业分包']];
        } else {
            $where[] = ['b.dw_type', '=', $type];
        }
        $result = ProjectZrrDetailModel::alias('a')
            ->field('a.id,a.zrr_name,zrr_position')
            ->leftJoin('t_project_zrr b', 'a.link_id = b.id')
            ->where($where)
            ->select();
        $this->success('success', $result);
    }

    /**
     * 项目名称数据整合
     * @param $data
     * @param $project_array
     * @return array
     */
    private function projectNameConvent($data, $project_array)
    {
        $res = [];
        foreach ($data as $k => $v) {
            if (isset($v['children'])) {
                $res[] = [
                    'name' => $project_array[$k]['name'],
                    'id' => $project_array[$k]['id'],
                    'children' => $this->projectNameConvent($v['children'], $project_array),
                ];
            } else {
                $res[] = [
                    'name' => $project_array[$k]['name'],
                    'id' => $project_array[$k]['id'],
                    'count' => $v['count'],
                ];
            }
        }

        foreach ($res as &$v) {
            if (isset($v['children'])) {
                $v['count'] = array_sum(array_column($v['children'], 'count'));
            }
        }

        return $res;
    }
}
